#include "connect.h"

void _get_config(char *ip, char *port,
                 int *workernum // workernum ref
)
{
    FILE *fp = fopen("../config/server.config", "r");
    if (fp == NULL)
    {
        perror("fopen");
    }

    char buf[1024] = {0};
    fgets(buf, sizeof(buf), fp);

    char *token;
    token = strtok(buf, " ");
    strcpy(ip, token);

    token = strtok(NULL, " ");
    strcpy(port, token);

    token = strtok(NULL, " ");
    *workernum = atoi(token);

    fclose(fp);
}

int epollAdd(int epfd, int fd)
{
    struct epoll_event ev;
    ev.data.fd = fd;
    ev.events = EPOLLIN;
    int epoll_ctl_res = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
    ERROR_CHECK(epoll_ctl_res, -1, "epoll add error");
    return 0;
}

int epollDel(int epfd, int fd)
{
    int epoll_ctl_res = epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL);
    ERROR_CHECK(epoll_ctl_res, -1, "epoll delete error");
    return 0;
}

int _tcp_init(const char *ip, const char *port)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(sockfd, -1, "socket");
    int flag = 1;
    int res = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));

    ERROR_CHECK(res, -1, "setsockopt");
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(ip);
    addr.sin_port = htons(atoi(port));
    res = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
    ERROR_CHECK(res, -1, "bind");

    res = listen(sockfd, _LISTEN_QUEUE_SIZE);
    ERROR_CHECK(res, -1, "listen");

    // printf("tcp_init success.\n");// test only

    return sockfd;
}

// // unit test
// int main()
// {
//     char ip[128] = {0};
//     char port[128] = {0};
//     int workernum;
//     _get_config(ip, port, &workernum);
//     printf("ip = %s\n", ip);
//     printf("port = %s\n", port);
//     printf("wokernum = %d\n", workernum);
// }
